#ifndef MYSOCKETSRV_H
#define MYSOCKETSRV_H

#include <QObject>
#include <QMap>
#include <QMutex>
#include <QThread>
#include <QAbstractSocket>

QT_BEGIN_NAMESPACE
class MyCacheData;
class ReceiveData;
class QTcpServer;
class QTcpSocket;
QT_END_NAMESPACE

class TcpClient : public QObject
{
    Q_OBJECT
public:
    TcpClient(int _socketID,QTcpSocket* _pSocket);
    ~TcpClient();

    void myDestroy();
private:
    bool disconnectMyHost();
    bool destroyTcpSocket();
    int code(const unsigned char *buff, const int len, unsigned char *outbuf);
    int uncode(const unsigned char *buff, int len, unsigned char *outbuf);
signals:
    void socketDestroyed(int sid);
    void controlCmd(long devID, long pID, float val);
public slots:
    void devSend(int devID,int devType,QString name);
    void pointSend(int devID,int pID, int pType, QString name, float defval);
    void sendItem(int devID,int pID,int sc, int msc,float val);
    void dataReceived();
    void disObj();
private slots:
    void sockeError(QAbstractSocket::SocketError error);
private:
    int socketID;
    QTcpSocket* m_pSocket;
};

class MySocketSrv;

class ClientThread : public QThread
{
    Q_OBJECT
public:
    ClientThread(MySocketSrv *m_MySocketSrv,QObject *parent = Q_NULLPTR);
    ~ClientThread();

    void stopRun();
protected:
    virtual void run();
signals:

private:
    bool running;
    MySocketSrv *ptr_MySocketSrv;
};

class MySocketSrv : public QObject
{
    Q_OBJECT
public:
    MySocketSrv();
    ~MySocketSrv();

private:
    void init();
    bool isListen();
    void stopListen();
    void initInfoSend(TcpClient* tcpC);
signals:
    void sendItem(int devID,int pID,int sc, int msc,float val);
public slots:
    void writeData();
private slots:
    void newConnectionSlot();
    void control(long devID, long pID, float val);
    void disObjTcpAll();
    void disObjTcp(int sid);
private:
    MyCacheData *mycache;
    ReceiveData *m_ReceiveData;

    int listenPort;
    QTcpServer *m_pServer;
    int socketIndex;
    QMap<int,TcpClient*> m_pSockets;
    QMutex  mutex_client;
    ClientThread *m_ClientThread;
    unsigned int heartTime;
};

#endif // MYSOCKETSRV_H
